#TASK 20250728-1448 [代光发] [done] : 团队项目合作管理功能之列出全部任务


"""
任务扫描工具 - 扫描项目文件中特定格式的任务注释

使用说明:
1. 基本用法: python task_scanner.py
   - 扫描当前目录下所有.py/.md/.txt/.markdown文件
   - 输出所有匹配的任务注释

2. 参数说明:
   --name [姓名]  只显示指定人员的任务
   示例: python task_scanner.py --name 代光发

任务注释格式:
#TASK YYYYMMDD-HHMM [姓名][可选标签] : 任务描述
示例: #TASK 20250715-2114 [代光发] : 制定团队评分细则
"""

import os
import re
import argparse
from pathlib import Path
from openpyxl import load_workbook

def parse_task_content(content):
    """解析任务内容并返回结构化数据"""
    match = re.match(
        r'#TASK\s+(\d{8}-\d{4})\s+\[([^\]]+)\](?:\s+\[[^\]]+\])*\s*:\s*(.+)',
        content,
        re.IGNORECASE
    )
    if match:
        time, name, summary = match.groups()
        return {
            'time': time,
            'name': name,
            'summary': summary
        }
    return None

def find_task_comments(root_dir):
    """查找项目目录中特定格式的任务注释"""
    # 支持的扩展名
    extensions = ('.py', '.md', '.txt', '.markdown')
    
    tasks_found = []
    
    for dirpath, _, filenames in os.walk(root_dir):
        for filename in filenames:
            if filename.endswith(extensions):
                filepath = Path(dirpath) / filename
                try:
                    with open(filepath, 'r', encoding='utf-8') as f:
                        for line_num, line in enumerate(f, 1):
                            if '#TASK' in line.upper():
                                parsed = parse_task_content(line.strip())
                                if parsed:
                                    tasks_found.append({
                                        'file': str(filepath),
                                        'line': line_num,
                                        **parsed
                                    })
                except (UnicodeDecodeError, PermissionError) as e:
                    print(f"无法读取文件 {filepath}: {e}")
    
    return tasks_found

def get_unique_tasks_by_file(tasks):
    """按文件路径去重，保留每个文件时间最早的任务"""
    # 按时间排序（升序）
    sorted_tasks = sorted(tasks, key=lambda x: x['time'])
    
    file_task_map = {}
    for task in sorted_tasks:
        if task['file'] not in file_task_map:
            file_task_map[task['file']] = task
    return list(file_task_map.values())

def write_to_excel(tasks, excel_path):
    """将任务写入Excel文件"""
    try:
        wb = load_workbook(excel_path)
        ws = wb['Sheet1']
        
        # 获取姓名列索引映射
        name_cols = {cell.value: idx+1 for idx, cell in enumerate(ws[1]) if idx > 0}
        
        # 写入任务数据
        for task in tasks:
            # 查找日期行
            date_row = None
            for row in range(2, ws.max_row + 1):
                if ws.cell(row=row, column=1).value == task['time']:
                    date_row = row
                    break
            
            # 如果没有找到日期行，添加新行
            if date_row is None:
                date_row = ws.max_row + 1
                ws.cell(row=date_row, column=1, value=task['time'])
            
            # 写入任务到对应姓名列
            if task['name'] in name_cols:
                col = name_cols[task['name']]
                ws.cell(row=date_row, column=col, value=task['summary'])
        
        wb.save(excel_path)
    except Exception as e:
        print(f"写入Excel文件出错: {e}")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--name', help='只显示指定姓名的任务')
    parser.add_argument('--excel', help='指定Excel输出路径',
                       default='docs/team-work-guide/git-task-list.xlsx')
    args = parser.parse_args()

    project_root = os.getcwd()
    tasks = find_task_comments(project_root)
    
    if tasks:
        unique_tasks = get_unique_tasks_by_file(tasks)
        
        print(f"扫描完成，共找到{len(tasks)}条任务记录，去重后剩余{len(unique_tasks)}条")
        print("时间,姓名,任务摘要,相对路径")
        
        displayed_tasks = [
            task for task in unique_tasks
            if not args.name or args.name == task['name']
        ]
        
        # 输出所有符合条件的任务（按时间排序）
        for task in sorted(displayed_tasks, key=lambda x: x['time']):
            rel_path = os.path.relpath(task['file'], project_root)
            print(f"{task['time']},{task['name']},{task['summary']},{rel_path}")
        
        # 将任务写入Excel
        write_to_excel(displayed_tasks, args.excel)
        
        print(f"\n共找到了 {len(displayed_tasks)} 条相关任务")
        print(f"任务已写入Excel文件: {args.excel}")
    else:
        print("未找到匹配的任务注释")
